package com.fuhao.gatewayservice.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

@Component
public class LoginFilter extends ZuulFilter {
    /**
     * 过滤器类型：前置
     * @return
     */
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    /**
     * 过滤器执行顺序，越小越先执行
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 当前过滤器是否生效，true生效
     * @return
     */
    @Override
    public boolean shouldFilter() {
        //获取网关当前上下文对象
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        //这个方法就可以根据不同路径来判断是否拦截，true拦截，false不拦截,获取添加一些参数值给run
        //例如
        System.out.println(request.getRequestURI());
        //System.out.println(request.getRequestURL());
        if("/apigateway/order/api/v1/order/save".equalsIgnoreCase(request.getRequestURI())){
            return true;
        }
        return false;
    }

    /**
     * 具体过滤逻辑
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String token = request.getParameter("token");
        if(StringUtils.isEmpty(token)){
            token  = request.getHeader("token");
        }
        if(StringUtils.isEmpty(token)){
            //表示不往下走了
          context.setSendZuulResponse(false);
            //响应状态码
          context.setResponseStatusCode(HttpStatus.FORBIDDEN.value());//未授权
        }
        return null;
    }
}
